package com.demo.thread.bbp;

/**
 * @author : YU.TAN
 * @date : 2021/11/5 13:43
 * 模拟容器
 */
public class SyncStack {
    int index = 0;
    /**
     * 构造馒头数组，相当于馒头筐，容量是6
     */
    SteamBread[] stb = new SteamBread[6];

    /**
     * 入栈
     * @param steamBread
     */
    public synchronized void push(SteamBread steamBread) {

        //满栈  线程等待
        while (index == stb.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //唤醒在此对象监视器上等待的单个线程，即消费者线程
        this.notify();
        stb[index] = steamBread;
        this.index++;
    }

    /**
     * 出栈
     * @param steamBread
     * @return
     */
    public synchronized SteamBread pop(){
        while (index==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        this.index--;
        //push第n个之后，this.index++，使栈顶为n+1，故return之前要减一
        return stb[index];
    }
}
